//
//  Instance.m
//  InheritedSingleton
//
//  Created by Xwoder on 2017/12/1.
//  Copyright © 2017年 Xwoder. All rights reserved.
//

#import "Instance.h"
#import <objc/runtime.h>

static dispatch_semaphore_t _semaphore;

@implementation Instance

+ (void)load {
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _semaphore = dispatch_semaphore_create(1);
    });
}

+ (instancetype)sharedInstance {
    Class selfClass = [self class];
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    id _instance = objc_getAssociatedObject(selfClass, @selector(sharedInstance));
    if (!_instance) {
        _instance = [[selfClass alloc] init];
        objc_setAssociatedObject(selfClass, @selector(sharedInstance), _instance, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    dispatch_semaphore_signal(_semaphore);
    return _instance;
}

@end
